package fr.upmc.i3s.upmcontact.tools;

import fr.upmc.i3s.upmcontact.callbacks.ISwipeCallback;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class SwipeDetector implements OnTouchListener {
	
	private static final int MIN_DISTANCE = 100;
	private float downX, upX;
//	private float downY, upY;
	private Action mSwipeDetected = Action.NONE;
	private ISwipeCallback callback;

	public static enum Action {
		FROM_L_TO_R, 	// Left to Right
		FROM_R_TO_L, 	// Right to Left
		FROM_T_TO_B, 	// Top to bottom
		FROM_B_TO_T, 	// Bottom to Top
		NONE, 			// when no action was detected
		CLICK
	}
	
	public SwipeDetector(ISwipeCallback callback) {
		super();
		this.callback = callback;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		
			case MotionEvent.ACTION_DOWN: {
				downX = event.getX();
//				downY = event.getY();
				mSwipeDetected = Action.NONE;
				return false;
			}
			
			case MotionEvent.ACTION_UP: {
				upX = event.getX();
//				upY = event.getY();
	
				float deltaX = downX - upX;
//				float deltaY = downY - upY;
	
				/* horizontal swipe detection */
				if (Math.abs(deltaX) > MIN_DISTANCE) {
					
					if (deltaX < 0) {
						mSwipeDetected = Action.FROM_L_TO_R;
						callback.perfomedSwipe(v, Action.FROM_L_TO_R);
						return false;
					}
					
					if (deltaX > 0) {
						mSwipeDetected = Action.FROM_R_TO_L;
						callback.perfomedSwipe(v, Action.FROM_R_TO_L);
						return false;
					}
				}
				
				 else
				 
//				 // vertical swipe detection if (Math.abs(deltaY) > MIN_DISTANCE)
//				 { // top or down if (deltaY < 0) { Log.i(logTag,
//				 "Swipe Top to Bottom"); mSwipeDetected = Action.TB; return false;
//				 } if (deltaY > 0) { Log.i(logTag, "Swipe Bottom to Top");
//				 mSwipeDetected = Action.BT; return false; } }
				 
				mSwipeDetected = Action.CLICK;
				return false;
			}
		}
		return false;
	}
	
	public boolean swipeDetected() {
		return mSwipeDetected != Action.NONE;
	}

	public Action getAction() {
		return mSwipeDetected;
	}

}